<template>
  <div class="container">
    <div class="regist">
      <div class="wrapper">
        <div class="welcome">欢迎注册为 核客论坛 会员</div>
        <form class="regist-body" autocomplete="off">
          <table cellpadding="0" cellspacing="0">
            <tr>
              <td><label for="userName">用户名：</label></td>
              <td>
                <i class="iconfont required-pic">&#xe618;</i>
                <input type="text" id="userName" v-model="registInfo.userName" autofocus="autofocus" class="registInput"/>
              </td>
              <td>
                <i class="iconfont hintIcon"></i>
                <span class="hint"></span>
              </td>
            </tr>
            <tr>
              <td><label for="passWord">密码：</label></td>
              <td>
                <i class="iconfont required-pic">&#xe618;</i>
                <input type="passWord" id="passWord" 
                  class="registInput"
                  style="ime-mode:disabled" 
                  v-model="registInfo.passWord"
                  @input="inputContentProgress"
                />
              </td>
              <td>
                <i class="iconfont passWordIcon hintIcon"></i>
                <span class="hint passWordHint"></span>
                <div class="progressBar" v-show="showProgress">
                  <div class="progress">
                    <div class="bar"></div>
                  </div>
                  <div class="level"></div>
                </div>
              </td>
            </tr>
            <tr>
              <td><label for="repassWord">确认密码：</label></td>
              <td>
                <i class="iconfont required-pic">&#xe618;</i>
                <input type="passWord" id="repassWord" v-model="registInfo.repassWord" class="registInput"/>
              </td>
              <td>
                <i class="iconfont hintIcon"></i>
                <span class="hint"></span>
              </td>
            </tr>
            <tr>
              <td><label for="email">邮箱：</label></td>
              <td>
                <i class="iconfont required-pic">&#xe618;</i>
                <input type="text" id="email" v-model="registInfo.email" class="registInput"/>
              </td>
              <td>
                <i class="iconfont hintIcon"></i>
                <span class="hint"></span>
              </td>
            </tr>
            <tr>
              <td><label for="registreson">注册原因：</label></td>
              <td>
                <i class="iconfont required-pic">&#xe618;</i>
                <textarea id="registreson" v-model="registInfo.registreson"></textarea>
              </td>
              <td>
                <i class="iconfont hintIcon"></i>
                <span class="hint"></span>
              </td>
            </tr>
            <tr>
              <td><label for="homeAddress">现居地址：</label></td>
              <td>
                <i class="iconfont required-pic">&#xe618;</i>
                <span id="homeAddress" v-model="registInfo.homeAddress"></span>
                <span style="color: #105cb6" 
                  @click="handleRegistPropShow"
                  id="addressBtn"
                >选择</span>
              </td>
              <td>
                <i class="iconfont hintIcon"></i>
                <span class="hint"></span>
              </td>
            </tr>
            <tr>
              <td><label for="qq">qq：</label></td>
              <td>
                <i class="iconfont required-pic">&#xe618;</i>
                <input type="text" id="qq" v-model="registInfo.qq" class="registInput"/>
              </td>
              <td>
                <i class="iconfont hintIcon"></i>
                <span class="hint"></span>
              </td>
            </tr>
            <tr>
              <td></td>
              <td>
                <button class="commit" @click="postAllRegistInfo">
                  同意以下协议并注册
                </button>
              </td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td class="rule" @click="handleRuleShow">《本站协议规章内容》</td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td colspan="2">
                <regist-rule v-if="showRule"></regist-rule>  
            </td>
            </tr>
          </table>
        </form>
        <!-- 侧边栏 -->
        <regist-aside></regist-aside>
      </div>
    </div>
    <address-prop 
      id="address-pop"
      v-show="showCity" 
      @close="showCity = false"
      @saveAddress="saveAddress"
    >
    </address-prop>
    <alert-prop 
      v-if="showAlert" 
      :fromText="'登陆'" 
      :toText="'注册'" 
      :toRoute="'/home'">
    </alert-prop>
  </div>
</template>

<script>
import axios from 'axios';
import { http } from 'common/verify.js';
import RegistRule from './component/RegistRule.vue';
import RegistAside from './component/RegistAside.vue';
import AddressProp from './component/AddressProp.vue';
import AlertProp from 'common/alert/AlertProp.vue';
export default {
  name: 'Regist',
  components: {
    RegistRule,
    RegistAside,
    AddressProp,
    AlertProp
  },
  data () {
    return {
      registInfo: {
        userName: '',
        passWord: '',
        repassWord: '',
        email: '',
        registreson: '',
        homeAddress: '',
        qq: ''
      },
      showRule: false,
      showProgress: false,
      showCity: false,
      showAlert: false,
      safeFlag: null,
      //顺序分别是borderColor,trColor,iconCode,iconColor,hintColor
      inputStyle: {
        focusStyle:['#99d8f5','#eff7fe','&#xe6b7;','#ccc','#999'],
        blurStyle:['#ccc','#fff','&#xe6b7;','#fff','#fff'],
        errorStyle:['#ccc','#fff','&#xe600;','#ec2716','#b52828'],
        okStyle :['#ccc','#fff','&#xe625;','#52bb17','#fff']
      },
      hintText: {
        userName: {
          focus: '2-5位，不能有空格,支持字母、数字、下划线和小数点',
          void: '用户名不能为空',
          errorLen: '用户名长度错误，长度控制在2-5位，不能有空格',
          errorCode: '用户名含有非法字符，请选择其他用户名',
          errorRepeat: '该用户名已被占用'
        },
        passWord: {
          focus: '密码最小长度6个字，最大长度12个字',
          void: '密码不能为空',
          errorLen: '密码长度错误，长度控制在6-15位'
        },
        repassWord: {
          focus: '请再输入一遍您上面填写的密码',
          void: '确认密码不能为空',
          error: '两次输入的密码不一致，请重新输入'
        },
        email: {
          focus: '请填写真实的电子邮箱',
          void: '邮箱不能为空',
          errorCode: '请输入正确的邮箱格式',
          errorRepeat: '该邮箱已被占用'
        },
        registreson: {
          focus: '注册原因是管理员判断是否通过审核的主要参考依据',
          void: '注册原因不能为空'
        },
        homeAddress: {
          void: '现居地址不能为空'
        },
        qq: {
          focus: '请填写真实的qq',
          void: 'qq不能为空'
        }
      }
    }
  },
  mounted () {
    this.handleFocusChange();
    this.handleBlurChange();
    this.homeAddressHint();
  },
  methods: {
    homeAddressHint() {
      const hint = $('#homeAddress').parent().next().children('span');
      if ($('#homeAddress').text()!==''){
        this.inputStyleChange($('#homeAddress'),this.inputStyle.okStyle);
      }
    },
    handleRuleShow () {
      if (this.showRule) {
        this.showRule = false;
      }else{
        this.showRule = true;
      }
    },
    handleFocusChange () {
      const _this = this;//important
      const allInput = $('.registInput');
      const textarea = $('textarea');

      allInput.on('focus',function(){
        //统一：边框颜色变化、父元素背景色、图标、提示文字变更
        const hint = $(this).parent().next().children('span');
        const id = $(this).attr('id');
        _this.inputStyleChange($(this),_this.inputStyle.focusStyle);
        hint.text(_this.hintText[id].focus);
      });
      textarea.on('focus',function(){
        //统一：边框颜色变化、父元素背景色、图标、提示文字变更
        const hint = $(this).parent().next().children('span');
        const id = $(this).attr('id');
        _this.inputStyleChange($(this),_this.inputStyle.focusStyle);
        hint.text(_this.hintText[id].focus);
      });
    },
    handleBlurChange () {
      var _this = this;//important
      var allInput = $('.registInput');
      var textarea = $('textarea');

      //当输入为空，提示不能为空
      allInput.on('blur', function(){
        //失去焦点的样式：边框和tr背景取消
        _this.inputStyleChange($(this),_this.inputStyle.blurStyle);
        //失去焦点取消progress
        _this.showProgress = false;
        //定义经常用到的变量
        const val = $(this).val();
        const len = $(this).val().length;
        const trimVal = val.replace(/\s/g,"");
        const id = $(this).attr('id');
        const hint = $(this).parent().next().children('span');
        if (len == 0 || trimVal == '') {
          //当没有输入任何字符或输入字符为全空格，显示错误
          _this.inputStyleChange($(this),_this.inputStyle.errorStyle);
          hint.text(_this.hintText[id].void);
        }else{
          //当id为userName
          if (id == 'userName') {
            const patrn=/[`~!@#$%^&*()+<>?:"{},\/;'[\]]/im;
            if (len == 1 && val.substr(0,1) == '0') {
              //第一个字符是0，且长度只为1，提示为空
              _this.inputStyleChange($(this),_this.inputStyle.errorStyle);
              hint.text(_this.hintText[id].void);
            }else if( len < 2 || len > 6 || val.indexOf(' ') != -1){
              //字符长度不符合要求，或者有空格
              _this.inputStyleChange($(this),_this.inputStyle.errorStyle);
              hint.text(_this.hintText[id].errorLen);
            }else if(patrn.test(val)){
              //测试非法字符
              _this.inputStyleChange($(this),_this.inputStyle.errorStyle);
              hint.text(_this.hintText[id].errorCode);
            }else{
              //前端完美还要掉后端，难受，想哭
              _this.getuserName();
            }
          }

          //当id为passWord
          if (id == 'passWord') {
            if ( len > 15 || len < 6) {
              //字符长度不合法的
              _this.inputStyleChange($(this),_this.inputStyle.errorStyle);
              hint.text(_this.hintText[id].errorLen);
            }else{
              _this.inputStyleChange($(this),_this.inputStyle.okStyle);
            }
          }

          //当id为repassWord
          if (id == 'repassWord') {
            if (val !== $('#passWord').val()) {
              _this.inputStyleChange($(this),_this.inputStyle.errorStyle);
              hint.text(_this.hintText[id].error);
            }else{
              _this.inputStyleChange($(this),_this.inputStyle.okStyle);
            }
          }

          //当id为email
          if (id == 'email') {
            const patrn = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g;
            if (!patrn.test(val)) {
              _this.inputStyleChange($(this),_this.inputStyle.errorStyle);
              hint.text(_this.hintText[id].errorCode);
            }else{
              _this.inputStyleChange($(this),_this.inputStyle.okStyle);
            }
          }

          //当id为qq
          if (id == 'qq') {
            _this.inputStyleChange($(this),_this.inputStyle.okStyle);
          }
        }
      });

      //注册原因textarea
      textarea.on('blur',function () {
        //失去焦点的样式：边框和tr背景取消
        _this.inputStyleChange($(this),_this.inputStyle.blurStyle);
        //定义经常用到的变量
        const len = $(this).val().length;
        const val = $(this).val();
        const trimVal = val.replace(/\s/g,"");
        const id = $(this).attr('id');
        const hint = $(this).parent().next().children('span');
        if (len == 0 || trimVal == '') {
          //当没有输入任何字符或输入字符为全空格，显示错误
          _this.inputStyleChange($(this),_this.inputStyle.errorStyle);
          hint.text(_this.hintText[id].void);
        }else{
          _this.inputStyleChange($(this),_this.inputStyle.okStyle);
        }
      });
    },
    inputStyleChange (el,[borderColor,trColor,iconCode,iconColor,hintColor]) {
      //定义必须常量
      const hint = el.parent().next().children('span');
      const icon = el.parent().next().children('i');
      const tr = el.parent().parent();
      //改变input焦点获取、失去焦点、输入错误、输入正确等样式
      el.css({ 'border': '1px solid '+borderColor+''});
      tr.css({ 'background': ''+trColor+''});
      icon.html(''+iconCode+'').css({'color': ''+iconColor+''});
      hint.css({'color':''+hintColor+''});
    },
    inputContentProgress () {
      //定义必须常量
      const hint = $('.passWordHint');
      const icon = $('.passWordIcon');
      const content = $('#passWord').val();
      const len = content.length;
      const _this = this;

      //清空提示文字和图标
      icon.html('');
      hint.html('');

      //输入值的同时，显示progress
      this.showProgress = true;

      //data立一个flag进行多个数据的同步操作
      function AnalyzepassWordSecurityLevel(passWord) {
        if (passWord.length == 0) {
          _this.safeFlag = 0;
        }else {
          if (/[a-z]/.test(passWord)){
              _this.safeFlag++ ;//lowercase
          }
          if (/[A-Z]/.test(passWord)){
              _this.safeFlag++;//uppercase
          }
          if(/[0-9]/.test(passWord)){
              _this.safeFlag++;//digital
          }
          if(containSpecialChar(passWord)){
              _this.safeFlag++;//specialcase
          }
          return _this.safeFlag;
        }
      }
      function containSpecialChar(str){   
        var containSpecial = RegExp(/[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/);
        return (containSpecial.test(str));   
      }

      //不同等级有不同的样式，爱我你怕了么
      const lowermsg = ['#bf2638','20%','弱'];
      const lowmsg = ['#bf9e26','40%','弱'];
      const midiummsg = ['#269efb','60%','中'];
      const highmsg = ['#39ac52','100%','强'];
      
      //调用密码输入的值校验方法
      //系数为0，显示为默认样式；系数小于3，显示为lower;
      //系数大于等于3小于6为low;系数大于6小于9为中级；系数大于9为高级
      var safeNumber = AnalyzepassWordSecurityLevel(content);
      if (len == 0){
        _this.safeFlag = 0;
        changeStyle(lowmsg);
      }else{
        if(len> 0 && len < 6){
          if(safeNumber <= 3){
            changeStyle(lowermsg);
          }else{
            changeStyle(lowmsg);
          }
        }else if(len >= 6 && len > 9){
          if(safeNumber > 6 && safeNumber <= 9) {
            changeStyle(midiummsg);
          }
        }else if(len >= 9) {
          if(safeNumber > 9) {
            changeStyle(highmsg);
          }
        }
      }

      //改变progress样式
      function changeStyle ([color,value,level]){
        $('.progress').css({'border':'1px solid '+color+''});
        $('.bar').css({'background':''+color+'','width':''+value+''});
        $('.level').text(''+level+'');
      };
    },
    handleRegistPropShow (){
      this.showCity = true;
      $('#address-pop').show();
    },
    getuserName () {
      const _this = this;
      axios.get(http+':8080/user/exists/'+_this.registInfo.userName)
        .then(function(response){
          const hint = $('#userName').parent().next().children('span');
            if(response.data !== 0){
              console.log(response.data);
              _this.inputStyleChange($('#userName'),_this.inputStyle.errorStyle);
              hint.text(_this.hintText.userName.errorRepeat);
            }else{
              _this.inputStyleChange($('#userName'),_this.inputStyle.okStyle);
            }
        }).catch(function (error) {
        　　console.log(error);
        });
    },
    saveAddress (el) {
      $('#homeAddress').text(el);
      if (($('#homeAddress').text())!==''){
        this.inputStyleChange($('#homeAddress'),this.inputStyle.okStyle);
      }
    },
    postAllRegistInfo () {
      const hintIcon = $('.hintIcon');
      var succ = true;
      const _this = this;
      //检测内容是否为空，为空则不接下去执行，icon图标是否为正确，不是则不接下去执行
      if ($('#userName').val() == '') hintForVoid ($('#userName'));
      if ($('#passWord').val() =='') hintForVoid ($('#passWord'));
      if ($('#repassWord').val() == '') hintForVoid ($('#repassWord'));
      if ($('#email').val() == '')  hintForVoid ($('#email'));
      if ($('#homeAddress').text() == '') hintForVoid ($('#homeAddress'));
      if ($('#registreson').val() == '') hintForVoid ($('#registreson'));
      if ($('#qq').val() == '') hintForVoid ($('#qq'));
      
      hintIcon.each(function(index, el) {
        if ($(this).css('color')!=='rgb(82, 187, 23)'){
          succ = false;
        }
      });

      function hintForVoid (el) {
        const hint = el.parent().next().children('span');
        const id = el.attr('id');
        _this.inputStyleChange(el,_this.inputStyle.errorStyle);
        hint.text(_this.hintText[id].void);
        succ = false
      }
      //传数据
      if (succ === true) {
        const registData = _this.registInfo
        //将数据转换成你要的样子
        const finaldata = JSON.stringify(registData);
        axios({
          method: 'post',
          url: ''+http+':8080/user',
          headers:{
            'token': ''+_this.responseData+'',
            'Content-type': 'application/json'
          },
          data: finaldata
        }).then(function(response){
          if(response.data.code == 0){
            _this.showAlert = true;
            setTimeout(function() {
              _this.$router.push({ path: '/login'});
              _this.showAlert = false;
            },5000)
            
          }
        }).catch(function (error) {
        　　console.log(error);
        });
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~assets/css/mixins.styl';
  .registInput,textarea
    width: 4.47rem
    height: .56rem
    border: 1px solid $borderColor
  td
    padding: .36rem 0
  textarea 
    row: 4
    height: 1.6rem
  table tr td:nth-child(1)
    width: 2.54rem
    text-align: right
  table tr td:nth-child(2)
    width: 5.46rem
    text-align: left
  table tr td:nth-child(3)
    width: 6rem
  .container
    container()
    padding-top: $spaceHeight
    .regist
      width: 100%
      .wrapper
        wrapper()
        .welcome
          width: 100%
          padding: .3rem 0px .3rem .3rem
          margin-bottom: .4rem
          font-size: .32rem
          font-weight: bold
          font-family: 'Microsoft YaHei'
          color: $font-welcome
          border: 1px solid $bgcolor-all
        //注册表格
        .regist-body
          padding: 0 .3rem
          width: 14rem
          .required-pic
            color: #ff0000
            font-size: .16rem
            vertical-align: middle
          .iconfont
            vertical-align: middle
          .hint
            font-size: .26rem
          .commit
            width: 3.5rem
            height: .64rem
            vertical-align: middle
            margin-left: .24rem
            color: $bgcolor-white
            background: linear-gradient(to bottom, #64b9df , #3776bf)
            border: .01rem solid #0c497c
          .commit:hover
            cursor: pointer
            background: linear-gradient(to bottom, #56a8d7 , #3776bf)
          .rule
            color: $font-blue
          .rule:hover
            text-decoration: underline
            cursor: pointer
          .progressBar
            width: 100%
            height: .28rem
            .progress
              float: left
              border: .02rem solid #bf9e26
              height: .24rem
              width: 45%
              text-align: left
              .bar
                height: .2rem
                background: #bf9e26
                width: 20%
                margin: .02rem
              .level
                float: left
                margin-left: .16rem
</style>